import Vue from 'vue'
import VueRouter from 'vue-router'

import login from '@/views/user/login.vue'

import home from '@/views/home/home.vue'
import qa from '@/views/qa/qa.vue'
import movie from '@/views/movie/movie.vue'
import notfound from '@/views/notFound/notFound.vue'
import { getToken } from '@/utils/token'
import search from '@/views/home/search.vue'
import searchResult from '@/views/home/searchResult.vue'
import leftMenu from '../components/leftMenu/leftMenu.vue'
import news from '@/views/news/news.vue'
import column from '@/views/column/column.vue'

Vue.use(VueRouter)

const routes = [
  {
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'home',
    path: '/home',
    component: home,
    // 接收路由元信息
    meta: { showTab: true }
  },

  {
    name: 'movie',
    path: '/movie',
    component: movie,
    // 接收路由元信息
    meta: { showTab: true }

  },
  {
    name: 'qa',
    path: '/qa',
    component: qa,
    // 接收路由元信息
    meta: { showTab: true }

  },
  // {
  //   name: 'user',
  //   path: '/user',
  //   component: user,
  //   // 接收路由元信息
  //   meta: {
  //     showTab: true, isLogin: true
  //   }

  // },
  {
    name: 'notfound',
    path: '/notfound',
    component: notfound
  },
  {
    name: 'search',
    path: '/search',
    component: search
  },
  {
    name: 'searchResult',
    path: '/searchResult',
    component: searchResult
  },
  {
    name: 'leftMenu',
    path: '/leftMenu',
    component: leftMenu
  },
  {
    name: 'news',
    path: '/news',
    component: news,
    meta: { showTab: true }
  },
  {
    name: 'column',
    path: '/column',
    component: column
  },
  // 路由重定向
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '*',
    redirect: '/notfound'
  }

]

const lc = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, A, B) {
  if (A || B) {
    return lc.call(this, location, A, B)
  }
  return lc.call(this, location).catch(err => { })
}

// /* 去掉路由跳转reject异常提示
// 注意：我们是直接修改VueRouter的原型，所以需要在实例化之前调用
// */
// //(1)先保存路由原型链中默认的跳转函数
// const originalPush = VueRouter.prototype.push
// //(2)替换原型链中的push
// VueRouter.prototype.push = function push(location, onResolve, onReject) {
//     if (onResolve || onReject) {
//         // 正常执行
//         //originalPush.call() : 我们自定义的push底层还是调用默认的push
//         return originalPush.call(this, location, onResolve, onReject)
//     }
//     //如果有异常，本来这个err默认是抛出的，我们直接不做任何处理（给吞掉了）
//     /*
//     底层默认是抛出异常：err => {throw err}
//     我们不抛出，不做任何处理：err => err
//     */
//     return originalPush.call(this, location).catch(err => err)
// }

console.log(VueRouter.prototype)
const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  // ...
  if (to.meta.isLogin && !getToken()) {
    next({ path: '/login' })
  } else {
    next()
  }
})

export default router
